<script lang="ts" setup>
import {ref, onMounted, watch} from 'vue';
import {useTurnStore} from "@/stores/turn.ts";
import * as echarts from 'echarts';
import china from 'echarts/map/json/china.json'; // 直接导入 JSON 文件
import { ElMessage } from 'element-plus';

const chartDom = ref(null);
const turnStore = useTurnStore();
let chart: echarts.ECharts | null = null;
const maxNum = ref(100);

const findMax = () => {
  if (turnStore.allProvinceData.length !== 0) {
    maxNum.value = Math.max(...turnStore.allProvinceData.map(item => item.value));
  }
}

watch(
  ()=>turnStore.allProvinceData,
  ()=>initChart(),
  {deep:true}
);

function initChart() {
  if (chart) {
    chart.dispose();
  }
  chart = echarts.init(chartDom.value);
  findMax();
  // 直接使用 geoJson 数据，不需要等待 axios 请求
  echarts.registerMap('china', china);

  const option:echarts.EChartsOption = {
    grid: {
      top: 0,
    },
    tooltip: {
      trigger: 'item',
      formatter: function(params) {
        return `
          <div style="font-size: 14px; font-weight: bold; margin-bottom: 4px;">
            ${params.name}
          </div>
          <div style="color: rgba(255, 255, 255, 0.8);">
            案件数量: ${params.value || 0}
          </div>
        `;
      },
      backgroundColor: 'rgba(0, 0, 0, 0.8)',
      borderColor: 'rgba(255, 255, 255, 0.2)',
      textStyle: {
        color: '#fff'
      }
    },
    visualMap: {
      min: 0,
      max: maxNum.value,
      left: '3%',
      top: 'bottom',
      text: ['高', '低'],
      textStyle: {
        color: 'rgba(255, 255, 255, 0.8)'
      },
      inRange: {
        color: ['#e0ffff', '#02264a']
      },
      hoverLink: true,
      realtime: true,
      calculable: true,
      calculablePrecision: 2,
      itemWidth: 20,
      itemHeight: 140,
      borderWidth: 0,
      backgroundColor: 'rgba(0, 0, 0, 0.2)',
      borderColor: 'rgba(255, 255, 255, 0.2)',
      textGap: 10,
      precision: 0
    },
    series: [{
      type: 'map',
      map: 'china',
      zoom: 1,
      roam: true,
      layoutCenter: ['55%', '50%'],
      layoutSize: '110%',
      label: {
        show: true,
        color: "rgba(255, 255, 255, 0.8)",
        fontSize: 12,
      },
      data: turnStore.allProvinceData,
      itemStyle: {
        areaColor: '#f0f9ff',
        borderColor: 'rgba(24,144,255,0.4)',
        borderWidth: 1.5,
        shadowColor: 'rgba(0,0,0,0.1)',
        shadowBlur: 2,
        shadowOffsetY: 2
      },
      emphasis: {
        label:{
          color: "#fff",
          fontSize: 14,
          fontWeight: 'bold'
        },
        itemStyle: {
          areaColor: 'rgba(64,169,255,0.4)',
          borderColor: 'rgba(255,255,255,0.8)',
          borderWidth: 2,
        }
      },
      select: {
        label: {
          color: "#fff",
          fontSize: 14,
          fontWeight: 'bold'
        },
        itemStyle: {
          areaColor: 'rgba(64,169,255,0.6)',
          borderColor: 'rgba(255,255,255,0.8)',
          borderWidth: 2,
        }
      }
    }]
  };
  chart.setOption(option);
  window.addEventListener('resize', function () {
    chart?.resize();
  });

  // 添加点击事件
  chart.on('click', function (params) {
    if (turnStore.provinceList.length >= 4 && !turnStore.provinceList.includes(params.name)) {
      ElMessage.warning('最多只能选择4个省份');
      return;
    }

    if (!turnStore.provinceList.includes(params.name)) {
      turnStore.provinceList.push(params.name);
      // 高亮选中的省份
      chart?.dispatchAction({
        type: 'select',
        seriesIndex: 0,
        name: params.name
      });
    } else {
      // 如果已经选中，则取消选中
      const index = turnStore.provinceList.indexOf(params.name);
      turnStore.provinceList.splice(index, 1);
      chart?.dispatchAction({
        type: 'unselect',
        seriesIndex: 0,
        name: params.name
      });
    }
  });

  // 添加鼠标悬停事件
  chart.on('mouseover', function(params) {
    if (!turnStore.provinceList.includes(params.name) && turnStore.provinceList.length < 4) {
      chart?.dispatchAction({
        type: 'highlight',
        seriesIndex: 0,
        name: params.name
      });
    }
  });

  // 添加鼠标移出事件
  chart.on('mouseout', function(params) {
    if (!turnStore.provinceList.includes(params.name)) {
      chart?.dispatchAction({
        type: 'downplay',
        seriesIndex: 0,
        name: params.name
      });
    }
  });

  // 添加双击事件，用于重置地图
  chart.on('dblclick', function() {
    chart?.dispatchAction({
      type: 'dataZoom',
      start: 0,
      end: 100
    });
  });
  window.addEventListener('resize', function () {
    chart?.resize();
  });
}

// 监听省份列表变化，更新选中状态
watch(
  () => turnStore.provinceList,
  (newVal, oldVal) => {
    if (chart) {
      // 清除所有选中状态
      chart.dispatchAction({
        type: 'unselect',
        seriesIndex: 0
      });

      // 重新设置选中状态
      newVal.forEach(province => {
        chart.dispatchAction({
          type: 'select',
          seriesIndex: 0,
          name: province
        });
      });
    }
  },
  { deep: true }
);

// 监听清除按钮点击
watch(() => turnStore.clearProvinceList, (newVal) => {
  if (newVal) {
    // 清除所有选中的省份
    if (chart) {
      chart.dispatchAction({
        type: 'unselect',
        seriesIndex: 0
      });
    }
  }
}, { immediate: true });

watch(turnStore.over, () => {
  console.log(turnStore.over);
  initChart();
})

onMounted(() => {
  initChart()
});
</script>

<template>
  <div style="display: flex; flex-direction: column; align-items: center;">
    <div class="chart-title">
      2018年 12月份全国各地区案件数量
      <div class="chart-title-icon" v-if="!turnStore.over">
        <el-icon><RefreshRight /></el-icon>
      </div>
    </div>
    <el-divider style="width: 40%; margin: 10px; "/>
    <div ref="chartDom" class="chart"></div>
  </div>
</template>

<style lang="scss">
@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
.chart {
  width: 100%;
  height: 50vh;
  border-radius: 10px;
  margin-bottom: 5px;
}

.chart-title{
  display: flex;
  flex-direction: row;
  height: 30px;
  margin: 0;
  color: white;
  text-align: center;
  justify-content: center;
  align-items: center;
}

.chart-title-icon{
  display: flex;
  justify-content: center;
  align-items: center;
  margin-left: 10px;
  animation: rotate 1s linear infinite;
}
</style>
